<?php
require_once('start_session.php');

// header
//require_once("header.php");
// search bar
//require_once("search_bar.php");
// main contents page
//require_once("poll_list.php");
// side bar
//require_once("connect_info.php");

require_once("global_vars.php");
require_once("db_connect.php");
/*
echo "cookie : ".$_COOKIE['user_id']."<br >";
echo "s_ip : ".$_SESSION['ip']."<br >";
echo "s_con_time : ".$_SESSION['connect_time']."<br >";
echo "s_location :".$_SESSION['location']."<br >";

echo "s_location_type :".$_SESSION['location_type']."<br >";	// string ("indoor" or "outdoor")
echo "s_latitude :".$_SESSION['latitude']."<br >";
echo "s_longitude :".$_SESSION['longitude']."<br >";
*/

$c_user_id = $_COOKIE['user_id'];
$s_ip = $_SESSION['ip'];
$s_con_time = $_SESSION['connect_time'];
$s_location = $_SESSION['location'];
$s_location_type = $_SESSION['location_type'];
$s_latitude = $_SESSION['latitude'];
$s_longitude = $_SESSION['longitude'];

//require_once("member_info.php");
// footer
?>


<?php
function distance($lat1, $lon1, $lat2, $lon2, $unit = 'M') {	//M = Miles
  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $dist = $dist * 60 * 1.1515;

  $unit = strtoupper ( $unit );
  if ($unit == "K") {	//K = Kilo Meters
    $dist *= 1.609344;
  } else if ($unit == "N") {
    $dist *= 0.8684;
  }

  return round($dist, 4);
}
?>

<html>
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>~설문설문~</title>
<script type="text/javascript" src="./js/util.js"></script>
</head>
<body>

<center><u style='font-size:17px;font-weight:bold'>참여가능한 신규등록 설문 알림창</u></center>
<br>

<?php
sleep(2);

$is_login = isset($_COOKIE['user_id']);
$user_id = $_COOKIE['user_id'];

$session_ip = $_SESSION['ip'];
$session_connect_time = $_SESSION['connect_time'];

$result = mysqli_query($conn, "select * from member where id = '$user_id'");
$member_row = mysqli_fetch_array($result);
/*
$member_row[id]
$member_row[passwd]
$member_row[name]
$member_row[gender]
$member_row[age]
$member_row[edulevel]
$member_row[phone]
$member_row[birth]
$member_row[email]
$member_row[addr]
$member_row[answer_count]
$member_row[make_count]
*/

$avail = 0;
$notavail = 0;

$query = "select * from survey where view_count <= 1";

if($user_id != '')
	$query = $query." and member_id <> '$user_id'";

//echo $query;
	
$survey_result = mysqli_query($conn, $query);
while($survey_row = mysqli_fetch_array($survey_result))
{
	/*
	$survey_row[id]
	$survey_row[title];
	$survey_row[is_once];
	$survey_row[start_date];
	$survey_row[end_date];
	$survey_row[start_time];
	$survey_row[end_time];
	$survey_row[max_capacity];
	$survey_row[require_login];
	$survey_row[ap_id];
	$survey_row[gps_id];
	$survey_row[category];
	$survey_row[member_id];
	$survey_row[view_count];
	*/
	
//	echo "<br>$survey_row[id]<br>";
	
	
	//1. 위치조건 만족
	$condition_satisfy_location = 0;
	if($survey_row[ap_id] != NULL)	//ap조건이 있는 경우 만족하면 통과
	{
		
		$query = "select ap_id from standard_ap where locatename = '$s_location' and ap_id = '$survey_row[ap_id]'";
//		echo $query;
		//의 결과가 한 튜플 나오면 만족.
		$result = mysqli_query($conn, $query);
		$result_rows = mysqli_num_rows($result);
		
		if($result_rows >= 1)
		{
//			echo "a";
			$condition_satisfy_location = 1;
		}
	}
	
	if($survey_row[gps_id] != NULL)	//gps조건이 있는 경우 만족하면 통과
	{
		$query = "select * from standard_gps where gps_id = '$survey_row[gps_id]'";
		$result = mysqli_query($conn, $query);
		$result_row = mysqli_fetch_array($result);
//		$result_row[latitude]
//		$result_row[longitude]
		
		$dist = distance($result_row[latitude], $result_row[longitude], $s_latitude, $s_longitude, 'K') * 1000;
		
//		echo "$result_row[radius] vs $dist<br>";
		
		if($result_row[radius] > $dist)
		{
//			echo "b";
			$condition_satisfy_location = 1;
		}
	}
	
	if($survey_row[ap_id] == NULL && $survey_row[gps_id] == NULL)	//위치조건이 없으면 접속자에 상관없이 통과
	{
		$condition_satisfy_location = 1;
	}

	
	//2. 참여가능한 날짜,시간대 만족
	$condition_satisfy_time = 0;
	/*
	$survey_row[start_date];
	$survey_row[end_date];
	$survey_row[start_time];
	$survey_row[end_time];
	*/
	
	//우선 현재시간(년월일시간분초)이 start_date(datetime)과 end_date(datetime) 범위에 속하는지 확인
	$query = "select now() from category where now() between '$survey_row[start_date]' and '$survey_row[end_date]'";
	$result1 = mysqli_query($conn, $query);
	$result1_rows = mysqli_num_rows($result1);
	
	//그다음 현재시간의 시간이 시간대가 맞는지 확인
	$query = "select cast(now() as time) from category where cast(now() as time) between '$survey_row[start_time]' and '$survey_row[end_time]'";
	$result2 = mysqli_query($conn, $query);
	$result2_rows = mysqli_num_rows($result2);
	
	if($result1_rows > 0 && $result2_rows > 0)
		$condition_satisfy_time = 1;
	
	
	//3. 설문의 기본조건이 있을 때, 로그인 되어 있는 회원이고 and 회원정보가 기본조건에 해당될때
	$condition_satisfy_basiccond = 0;
	//이 설문의 기본조건이 없으면, 바로 만족
	//기본조건이 있는데 회원로그인이 안되어있으면 불만족
	//기본조건이 있고 회원정보로 검색한 내용이 1레코드이상 나오면 만족
	//                                         0레코드이면 안만족

	$query = "select * from basic_condition where survey_id = '$survey_row[id]'";
	$result = mysqli_query($conn, $query);
	$result_rows = mysqli_num_rows($result);
	
	if($result_rows == 0)
	{
		//기본조건이 없다.
		$condition_satisfy_basiccond = 1;
	}
	else
	{
		//기본조건이 있다.
		if($is_login == 0)
		{
			//로그인이 안되어있으면 실패
			$condition_satisfy_basiccond = 0;
		}
		else
		{
			//로그인이 되어있으면, 기본조건들중 회원정보와 일치하는게 있는지 확인
			if($member_row[age] < 20) $member_cond_age = 10;
			else if($member_row[age] < 30) $member_cond_age = 20;
			else if($member_row[age] < 40) $member_cond_age = 30;
			else if($member_row[age] < 50) $member_cond_age = 40;
			else $member_cond_age = 50;
			
			$member_cond_edulevel = $member_row[edulevel];
			$member_cond_gender = $member_row[gender];
			$member_cond_addr = $member_row[addr];
			
			//select * from basic_condition where '서울시 어쩌구저쩌구' like CONCAT('%', addr, '%') and addr <> ''
			$query = "select * from basic_condition where survey_id = '$survey_row[id]' and (age = '$member_cond_age' or age = '0') and (edulevel = '$member_cond_edulevel' or edulevel = '') and (gender = '$member_cond_gender' or gender = '0') and (('$member_cond_addr' like CONCAT('%', addr,'%') and addr <> '') or addr = '')";
//			echo $query;
			
			$result = mysqli_query($conn, $query);
			$result_rows = mysqli_num_rows($result);
			if($result_rows >= 1)
			{
				$condition_satisfy_basiccond = 1;
			}
			else
			{
				$condition_satisfy_basiccond = 0;
			}
		}
	}

	
	//4. 1회성 설문인경우 - 아직참여하지 않은 경우
	$condition_satisfy_isonce = 0;
	//	 반복형 설문인경우 - 오늘 참여하지 않은 경우(answer테이블을 보면 알수 있음)

	if($survey_row[is_once] == 1) //반복형
	{
		if($is_login == 1)
		{	//회원인경우 이 survey에 대해 오늘 참여한 id가 answer에 없으면 통과1임
			$query = "select * from answer where survey_id = '$survey_row[id]' and mem_id = '$user_id' and cast(submit_time as date) = cast(now() as date)";
		}
		else
		{	//비회원(회원도 포함)인 경우 현재의 IP, connect time이 오늘참여한 answer에 없으면 통과1임
			$query = "select * from answer where survey_id = '$survey_row[id]' and ip = '$session_ip' and connect_time = '$session_connect_time' and cast(submit_time as date) = cast(now() as date)";
		}
	}
	else	//1회성 설문
	{
		if($is_login == 1)
		{	//회원인경우 이 survey에 대해 지금까지 참여한 id가 answer에 없으면 통과1임
			$query = "select * from answer where survey_id = '$survey_row[id]' and mem_id = '$user_id'";
		}
		else
		{	//비회원(회원도 포함)인 경우 현재의 IP, connect time이 answer에 없으면 통과1임
			$query = "select * from answer where survey_id = '$survey_row[id]' and ip = '$session_ip' and connect_time = '$session_connect_time'";
		}
	}
	$result = mysqli_query($conn, $query);
	$result_rows = mysqli_num_rows($result);
	if($result_rows == 0)
	{
		$condition_satisfy_isonce = 1;
	}
	
	
	//5. 참여인원이 비어있는 경우
	$condition_satisfy_capacity = 0;
	if($survey_row[max_capacity] == 0)	//참여가능인원이 무제한이므로 통과
	{
		$condition_satisfy_capacity = 1;
	}
	else								//참여가능인원이 유한하므로, 응답자수에 따라서 통과
	{
		$query = "select * from answer where survey_id = '$survey_row[id]'";
		$result = mysqli_query($conn, $query);
		$result_rows = mysqli_num_rows($result);
		if($survey_row[max_capacity] > $result_rows)
			$condition_satisfy_capacity = 1;	//아직 여유있음
		else
			$condition_satisfy_capacity = 0;	//꽉 차서 더이상 설문필요없음
	}
	
	
	//6. $survey_row[require_login] == 1인 경우, 현재로그인 상태인 경우
	$condition_satisfy_requirelogin = 0;
	if($survey_row[require_login] == 0)	//로그인 요구하지 않는 설문의 경우 다 통과
		$condition_satisfy_requirelogin = 1;
	else	//로그인 요구되었을때, 
	{
		if($is_login == 1) $condition_satisfy_requirelogin = 1;
		else $condition_satisfy_requirelogin = 0;
	}
	if($condition_satisfy_location == 1 && $condition_satisfy_time == 1 && $condition_satisfy_basiccond == 1 && $condition_satisfy_isonce == 1 && $condition_satisfy_capacity == 1 && $condition_satisfy_requirelogin == 1)
	{
		?>
		<b>설문이름</b> : <?=$survey_row[title]?>&nbsp;&nbsp;&nbsp;<input type=button value='참여하기' onclick="javascript:opener.parent.location.href='survey_participate.php?sid=<?=$survey_row[id]?>';self.close()"><br />
		<?
		
		mysqli_query($conn, "update survey set view_count=view_count+1 where id='$survey_row[id]' and view_count = 0");
		//echo "update survey set view_count=view_count+1 where id='$survey_row[id]' and view_count = 0";
	}
	else
	{

	}
}
?>

<script type="text/javascript">
<?
	if($avail > 0)
//	echo "win = openPopup(\"monitor_view.php\", \"newsurvey\", 400, 300);";
?>	

<?
	if($avail == 0)
//	echo "win.close();";
?>
</script>

</body>
</html>

<?
mysqli_close($conn);
?>

